package storage

import (
	"codeless/config"
	models "codeless/model"
	"codeless/utils"
	"errors"
	"io"
	"mime/multipart"
	"os"
	"path"
	"strings"
	"time"
)

type LocalStorage struct {
}

func (c *LocalStorage) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, src)
	return err
}
func (c *LocalStorage) Upload(fh *multipart.FileHeader) (*models.RestOss, error) {

	today := time.Now().Format("2006-01-02")
	dst := path.Join(config.GetAppConfig().Fs.Local.Path, today)
	extname := strings.ToLower(path.Ext(fh.Filename))
	if !utils.PathExists(dst) {
		os.MkdirAll(dst, os.ModePerm)
	}
	rId := utils.NewId()
	fileName := rId + extname
	realName := today + "/" + fileName
	if err := c.SaveUploadedFile(fh, path.Join(dst, fileName)); err != nil {
		return nil, err
	} else {
		resp := models.RestOss{
			Code:       0,
			Message:    "",
			Id:         rId,
			ObjectName: fileName,
			Url:        realName,
		}
		return &resp, nil
	}

}
func (c *LocalStorage) UploadPath(path string) (*models.RestOss, error) {
	return nil, errors.New("do nothing")
}
func (c *LocalStorage) Delete(name string) error {
	filePath := path.Join(config.GetAppConfig().Fs.Local.Path, name)
	if exist := utils.PathExists(filePath); exist {
		err := os.Remove(filePath)
		return err
	} else {
		return errors.New("not exists")
	}

}
